import json

import xmltodict
from django.shortcuts import render

# Create your views here.
from mws import mws
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from amazondatas.serializers import OrderItemForSKUSerializer, SKUSerializer
from orders.models import OrderItem, Orders
from amazondatas.models import SKU


access_key = 'AKIAJGOQGGTWX4ICHVZQ'  # replace with your access key

marketplaceids = ['A1AM78C64UM0Y8', 'A2EUQ1WTGCTBG2', 'ATVPDKIKX0DER']
marketplaceid_list = {
    "Amazon.ca": "A2EUQ1WTGCTBG2",
    "Amazon.com": "ATVPDKIKX0DER",
    "Amazon.com.mx": "A1AM78C64UM0Y8",
}
secret_key = 'SjLuwkvF46VCiPzmlFwP8+aPYjA7BNP3IazSyD0l'  # replace with your secret key
SellerId = "APW1B548Y33A8"
MWSToken = "amzn.mws.04b60bef-32f8-aa27-0820-c6802871b4e0"


class GetImage:
    pass


class GetImageView(APIView):

    def get(self, request):

        order_items = OrderItem.objects.filter(GoodsImage='')
        serializer = OrderItemForSKUSerializer(order_items, many=True)
        # print(serializer.data)
        # data_list = list()
        i = 0
        for order_item in serializer.data:
            print(order_item)
            # print(order_item.Order,type(order_item.Order))
            order = Orders.objects.get(id=order_item['Order'])

            # ASIN_list.append(order_item.ASIN)
            x = mws.Products(access_key=access_key, secret_key=secret_key, account_id=SellerId, auth_token=MWSToken)
            amazondatas = x.get_matching_product_for_id(marketplaceid=marketplaceid_list[order.SalesChannel],
                                                        type_="ASIN", ids=order_item['ASIN'])
            response_data = amazondatas.original
            xml_dict = xmltodict.parse(response_data)
            # print(xml_dict)
            if xml_dict['GetMatchingProductForIdResponse']['GetMatchingProductForIdResult']['@status'] == 'ClientError':
                continue
            else:
                # data_list.append(xml_dict['GetMatchingProductForIdResponse']['GetMatchingProductForIdResult']['Products']['Product']['AttributeSets']['ns2:ItemAttributes']["ns2:SmallImage"]['ns2:URL'])
                orderitem = OrderItem.objects.get(id=order_item['id'])
                orderitem.GoodsImage = xml_dict['GetMatchingProductForIdResponse']['GetMatchingProductForIdResult']['Products']['Product']['AttributeSets']['ns2:ItemAttributes']["ns2:SmallImage"]['ns2:URL']
                orderitem.save()
                # data_list.append(xml_dict['GetMatchingProductForIdResponse']['GetMatchingProductForIdResult']['Products']['Product']['AttributeSets']['ns2:ItemAttributes']["ns2:SmallImage"]['ns2:URL'])
                i += 1
        return Response({"success_msg": f"{i}张图片更新完毕"})


class GetSKUView(APIView):

    def get(self, request):

        order_items = OrderItem.objects.filter(sku=None)
        serializer = OrderItemForSKUSerializer(order_items, many=True)
        # print(serializer.data)
        data_list = list()
        i = 0
        for order_item in serializer.data:
            # print(order_item)
            # 考虑ASIN去重问题
            sku = SKU.objects.filter(ASIN=order_item['ASIN'])
            if len(sku) != 0:
                orderitem1 = OrderItem.objects.get(id=order_item['id'])
                orderitem1.sku = sku[0]
                orderitem1.save()
                continue
            # print(order_item.Order,type(order_item.Order))
            order = Orders.objects.get(id=order_item['Order'])

            # ASIN_list.append(order_item.ASIN)
            x = mws.Products(access_key=access_key, secret_key=secret_key, account_id=SellerId, auth_token=MWSToken)
            amazondatas = x.get_matching_product_for_id(marketplaceid=marketplaceid_list[order.SalesChannel],
                                                        type_="ASIN", ids=order_item['ASIN'])
            response_data = amazondatas.original
            xml_dict = xmltodict.parse(response_data)
            if xml_dict['GetMatchingProductForIdResponse']['GetMatchingProductForIdResult']['@status'] == 'ClientError':
                continue
            else:
                if xml_dict['GetMatchingProductForIdResponse']['GetMatchingProductForIdResult']['Products']['Product']['SalesRankings']:
                    rank = xml_dict['GetMatchingProductForIdResponse']['GetMatchingProductForIdResult']['Products']['Product']['SalesRankings'].get('SalesRank')
                    if isinstance(rank, list):
                        print(rank[0]['ProductCategoryId'], rank[0]['Rank'])
                        ProductCategoryId = rank[0]['ProductCategoryId']
                        Rank = rank[0]['Rank']
                    else:
                        ProductCategoryId = rank['ProductCategoryId']
                        Rank = rank['Rank']

                else:
                    ProductCategoryId = "暂无排名"
                    Rank = "暂无排名"
                SKUDATA = xml_dict['GetMatchingProductForIdResponse']['GetMatchingProductForIdResult']['Products']['Product']['AttributeSets']["ns2:ItemAttributes"]
                # print(SKUDATA)
                json_str = json.dumps(SKUDATA)
                json_str.strip('ns2:')
                new_json_str = json_str.replace('ns2:', '')
                SKUDATA = json.loads(new_json_str)
                # print(SKUDATA)
                SKUDATA['lang'] = SKUDATA.pop('@xml:lang')
                key_list = ['Binding', 'Brand', 'Color', 'Department', 'Label', 'Manufacturer', 'NumberOfItems',
                            'PackageQuantity', 'PartNumber', 'ProductGroup', 'ProductTypeName', 'Publisher',
                            'Size', 'Studio', 'Title']

                for j in key_list:
                    if j not in SKUDATA.keys():
                        SKUDATA[j] = '-'

                SKUDATA['SmallImage'] = SKUDATA['SmallImage']["URL"]

                SKUDATA['ASIN'] = order_item['ASIN']
                SKUDATA['SalesChannel'] = marketplaceid_list[order.SalesChannel]
                SKUDATA['ProductCategoryId'] = ProductCategoryId
                SKUDATA['Rank'] = Rank
                # print(SKUDATA)
                serializer = SKUSerializer(data=SKUDATA)
                serializer.is_valid()
                serializer.save()
                data_list.append(SKUDATA)
                i += 1
                if i == 10:
                    break
        return Response({"success_msg": f"{i}条SKU更新完毕"})

